﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using TCPActivePull.Config;

namespace TCPActivePull.Service;

public class TcpPollingAndForwardService : BackgroundService
{
    // Modbus设备默认端口（可根据需要改为配置项）
    private const int DefaultModbusPort = 502;
    private const ushort ModbusMaxRegisterCount = 125; // Modbus协议限制
    private const byte FixedUnitId = 1;            // 固定设备地址（UnitId=1）

    private readonly IndustrialConfig _config;
    private readonly ILogger<TcpPollingAndForwardService> _logger;
    private readonly TcpListener _tcpServer;
    private readonly ConcurrentDictionary<string, ClientConnection> _clientConnections = new();
    private readonly ConcurrentQueue<IndustrialData> _dataQueue = new();
    private Timer? _pollingTimer;
    private readonly JsonSerializerOptions _jsonOptions;
    private static int _transactionId = 1;
    private const int MaxDataQueueCount = 1000;

    // 日期时间JSON序列化转换器
    public class DateTimeConverterWithFormat : System.Text.Json.Serialization.JsonConverter<DateTime>
    {
        private readonly string _format;

        public DateTimeConverterWithFormat(string format)
        {
            _format = format;
        }

        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.Parse(reader.GetString()!);
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(_format));
        }
    }

    public TcpPollingAndForwardService(
        IOptions<IndustrialConfig> config,
        ILogger<TcpPollingAndForwardService> logger)
    {
        _config = config.Value ?? throw new ArgumentNullException(nameof(config));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));

        // 初始化JSON序列化配置
        _jsonOptions = new JsonSerializerOptions
        {
            WriteIndented = false,
            Converters = { new DateTimeConverterWithFormat("yyyy-MM-dd HH:mm:ss.fff") }
        };

        // 从配置读取IP和端口初始化TCP服务器
        if (!IPAddress.TryParse(_config.TcpServer.Ip, out var serverIp))
        {
            throw new ArgumentException($"无效的服务器IP地址: {_config.TcpServer.Ip}");
        }

        if (_config.TcpServer.Port < 1 || _config.TcpServer.Port > 65535)
        {
            throw new ArgumentException($"无效的服务器端口: {_config.TcpServer.Port}（必须在1-65535范围内）");
        }

        _tcpServer = new TcpListener(serverIp, _config.TcpServer.Port);
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            _tcpServer.Start();
            _logger.LogInformation($"TCP转发服务器启动：{_config.TcpServer.Ip}:{_config.TcpServer.Port}");
            Console.WriteLine($"TCP转发服务器启动：{_config.TcpServer.Ip}:{_config.TcpServer.Port}");
            Console.WriteLine($"设备采集周期：{_config.PollingIntervalMs}ms，客户端超时时间：10秒");

            // 启动客户端连接接收任务
            _ = AcceptClientConnectionsAsync(stoppingToken);

            // 初始化并启动轮询定时器
            _pollingTimer = new Timer(
                async _ => await PollAllDevicesAsync(stoppingToken),
                null,
                TimeSpan.Zero,
                TimeSpan.FromMilliseconds(_config.PollingIntervalMs)
            );
        }
        catch (Exception ex)
        {
            _logger.LogCritical(ex, "TCP服务器启动失败（IP：{Ip}，端口：{Port}）",
                _config.TcpServer.Ip, _config.TcpServer.Port);
            throw;
        }
        return Task.CompletedTask;
    }

    #region 客户端连接管理
    private async Task AcceptClientConnectionsAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                var client = await _tcpServer.AcceptTcpClientAsync(stoppingToken);
                var remoteEndPoint = client.Client.RemoteEndPoint?.ToString() ?? "未知地址";
                var clientId = $"CLIENT-{Guid.NewGuid():N}";
                var stream = client.GetStream();

                // 禁用Nagle算法，减少延迟
                client.NoDelay = true;

                if (_clientConnections.TryAdd(clientId, new ClientConnection
                {
                    Client = client,
                    Stream = stream,
                    ClientId = clientId,
                    LastActiveTime = DateTime.Now
                }))
                {
                    _logger.LogInformation($"客户端连接成功：{clientId}（{remoteEndPoint}）");
                    Console.WriteLine($"客户端连接成功：{clientId}（{remoteEndPoint}）");

                    // 启动客户端消息处理和活性监控任务
                    _ = ProcessClientMessagesAsync(clientId, stoppingToken);
                    _ = MonitorClientActivityAsync(clientId, stoppingToken);
                }
                else
                {
                    _logger.LogWarning($"客户端[{clientId}]添加到连接池失败，已断开");
                    Console.WriteLine($"客户端[{clientId}]添加到连接池失败，已断开");
                    client.Close();
                }
            }
            catch (OperationCanceledException)
            {
                _logger.LogInformation("客户端连接接收任务已取消（正常关闭）");
                Console.WriteLine("客户端连接接收任务已取消（正常关闭）");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "接受客户端连接异常，1秒后重试");
                Console.WriteLine($"接受客户端连接异常：{ex.Message}，1秒后重试");
                await Task.Delay(1000, stoppingToken);
            }
        }
    }

    private async Task ProcessClientMessagesAsync(string clientId, CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            if (!_clientConnections.TryGetValue(clientId, out var conn) || !conn.Client.Connected)
            {
                _logger.LogInformation($"客户端[{clientId}]连接失效，停止消息处理");
                Console.WriteLine($"客户端[{clientId}]连接失效，停止消息处理");
                break;
            }

            try
            {
                byte[] buffer = new byte[1024];
                using var readCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
                readCts.CancelAfter(5000); // 5秒读取超时

                int bytesRead = await conn.Stream.ReadAsync(buffer, 0, buffer.Length, readCts.Token);
                if (bytesRead == 0)
                {
                    _logger.LogInformation($"客户端[{clientId}]主动断开连接");
                    Console.WriteLine($"客户端[{clientId}]主动断开连接");
                    CleanClientConnection(clientId, conn);
                    break;
                }

                string clientMsg = Encoding.UTF8.GetString(buffer, 0, bytesRead).Trim();
                if (clientMsg.Equals("HEARTBEAT", StringComparison.OrdinalIgnoreCase))
                {
                    conn.LastActiveTime = DateTime.Now;
                    byte[] ackBytes = Encoding.UTF8.GetBytes("HEARTBEAT_ACK\n");
                    // 使用优化的WriteAsync重载
                    await conn.Stream.WriteAsync(new ReadOnlyMemory<byte>(ackBytes), stoppingToken);
                    _logger.LogDebug($"客户端[{clientId}]心跳包已响应");
                }
                else
                {
                    _logger.LogWarning($"客户端[{clientId}]发送未知消息：{clientMsg}，已忽略");
                    Console.WriteLine($"客户端[{clientId}]发送未知消息：{clientMsg}，已忽略");
                }
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug($"客户端[{clientId}]消息读取超时（5秒），继续监听");
                Console.WriteLine($"客户端[{clientId}]消息读取超时（5秒），继续监听");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理客户端[{clientId}]消息异常");
                Console.WriteLine($"处理客户端[{clientId}]消息异常：{ex.Message}");
                CleanClientConnection(clientId, conn);
                break;
            }
        }
    }

    private async Task MonitorClientActivityAsync(string clientId, CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            if (_clientConnections.TryGetValue(clientId, out var conn))
            {
                if (DateTime.Now - conn.LastActiveTime > TimeSpan.FromSeconds(10))
                {
                    _logger.LogInformation($"客户端[{clientId}]超时（10秒无活动），即将断开");
                    Console.WriteLine($"客户端[{clientId}]超时（10秒无活动），即将断开");
                    CleanClientConnection(clientId, conn);
                    break;
                }
            }
            else
            {
                _logger.LogInformation($"客户端[{clientId}]已从连接池移除，停止活性监控");
                Console.WriteLine($"客户端[{clientId}]已从连接池移除，停止活性监控");
                break;
            }
            await Task.Delay(1000, stoppingToken);
        }
    }

    private void CleanClientConnection(string clientId, ClientConnection? conn = null)
    {
        try
        {
            // 尝试从连接池获取并移除客户端连接
            if (conn == null)
            {
                _clientConnections.TryRemove(clientId, out conn);
            }
            else
            {
                _clientConnections.TryRemove(clientId, out _);
            }

            if (conn == null) return;

            // 释放资源
            conn.Stream?.Dispose();
            if (conn.Client.Connected)
            {
                conn.Client.Close();
            }

            _logger.LogInformation($"客户端[{clientId}]连接已清理");
            Console.WriteLine($"客户端[{clientId}]连接已清理");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"清理客户端[{clientId}]连接异常");
            Console.WriteLine($"清理客户端[{clientId}]连接异常：{ex.Message}");
        }
    }
    #endregion

    #region 设备数据采集
    private async Task PollAllDevicesAsync(CancellationToken stoppingToken)
    {
        if (!_config.Devices?.Any() ?? true)
        {
            _logger.LogInformation("未配置任何设备，跳过采集任务");
            Console.WriteLine("未配置任何设备，跳过采集任务");
            return;
        }

        _logger.LogInformation($"开始本轮设备采集，共{_config.Devices.Count}个设备");
        Console.WriteLine($"开始本轮设备采集，共{_config.Devices.Count}个设备");

        foreach (var device in _config.Devices)
        {
            if (stoppingToken.IsCancellationRequested) break;

            try
            {
                await PollSingleDeviceAsync(device, stoppingToken);
                await Task.Delay(100, stoppingToken); // 设备间采集间隔
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"采集设备[{device.DeviceId}]（IP：{device.DeviceIp}）失败，下一轮重试");
                Console.WriteLine($"采集设备[{device.DeviceId}]（IP：{device.DeviceIp}）失败：{ex.Message}，下一轮重试");
            }
        }
    }

    private async Task PollSingleDeviceAsync(DeviceConfig device, CancellationToken stoppingToken)
    {
        if (device == null)
        {
            _logger.LogWarning("设备配置为空，跳过采集");
            return;
        }

        _logger.LogInformation($"开始采集设备[{device.DeviceId}]（IP：{device.DeviceIp}）");
        Console.WriteLine($"开始采集设备[{device.DeviceId}]（IP：{device.DeviceIp}）");

        // 寄存器分组处理
        var registerGroups = GroupRegistersByContinuousAddress(device.Registers);
        if (!registerGroups.Any())
        {
            _logger.LogInformation($"设备[{device.DeviceId}]无有效寄存器配置，已跳过");
            Console.WriteLine($"设备[{device.DeviceId}]无有效寄存器配置，已跳过");
            return;
        }

        // 连接设备并采集数据
        using var deviceTcpClient = new TcpClient();
        NetworkStream? deviceStream = null;

        try
        {
            // 连接设备（5秒超时）
            using var connectCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
            connectCts.CancelAfter(5000);

            await deviceTcpClient.ConnectAsync(device.DeviceIp, DefaultModbusPort, connectCts.Token);
            deviceStream = deviceTcpClient.GetStream();

            _logger.LogInformation($"设备[{device.DeviceId}]（IP：{device.DeviceIp}）连接成功");
            Console.WriteLine($"设备[{device.DeviceId}]（IP：{device.DeviceIp}）连接成功");

            // 处理每个寄存器组
            foreach (var group in registerGroups)
            {
                if (!ushort.TryParse(group.StartAddr, out ushort startAddr) ||
                    !ushort.TryParse(group.Count.ToString(), out ushort regCount))
                {
                    _logger.LogWarning($"设备[{device.DeviceId}]寄存器配置无效：{group.StartAddr}-{group.EndAddr}");
                    Console.WriteLine($"设备[{device.DeviceId}]寄存器配置无效：{group.StartAddr}-{group.EndAddr}");
                    continue;
                }

                if (regCount > ModbusMaxRegisterCount)
                {
                    _logger.LogWarning($"设备[{device.DeviceId}]寄存器组数量[{regCount}]超过协议上限（{ModbusMaxRegisterCount}），已跳过");
                    Console.WriteLine($"设备[{device.DeviceId}]寄存器组数量[{regCount}]超过协议上限（{ModbusMaxRegisterCount}），已跳过");
                    continue;
                }

                // 创建Modbus请求
                ushort transactionId = GetNextTransactionId();
                byte[] request = ModbusHelper.CreateReadRequest(
           transactionId,
           FixedUnitId,
           startAddr,
           regCount,
           device.FunctionCode // 从设备配置读取功能码
       );

                // 验证请求有效性
                if (request == null || request.Length != 12)
                {
                    _logger.LogError($"设备[{device.DeviceId}]创建Modbus请求失败（无效长度：{request?.Length ?? 0}字节）");
                    Console.WriteLine($"设备[{device.DeviceId}]创建Modbus请求失败（无效长度：{request?.Length ?? 0}字节）");
                    continue;
                }

                // 发送请求 - 使用优化的WriteAsync重载
                await deviceStream.WriteAsync(new ReadOnlyMemory<byte>(request), stoppingToken);
                _logger.LogInformation($"向设备[{device.DeviceId}]发送请求：事务ID={transactionId}，起始寄存器{startAddr}（{regCount}个）");

                // 读取响应（3秒超时）
                byte[] responseBuffer = new byte[1024];
                int responseLen;

                using var readRespCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
                readRespCts.CancelAfter(3000);

                responseLen = await deviceStream.ReadAsync(responseBuffer, 0, responseBuffer.Length, readRespCts.Token);

                if (responseLen == 0)
                {
                    _logger.LogWarning($"设备[{device.DeviceId}]无响应数据");
                    Console.WriteLine($"设备[{device.DeviceId}]无响应数据");
                    continue;
                }

                // 解析响应
                byte[] response = responseBuffer.Take(responseLen).ToArray();
                var (parseSuccess, rawValues, errorMsg) = ModbusHelper.ParseResponse(response);

                if (!parseSuccess)
                {
                    if (response.Length >= 8 && (response[7] & 0x80) == 0x80)
                    {
                        byte errorCode = response[8];
                        string errorDesc = GetModbusErrorCodeDesc(errorCode);
                        errorMsg = $"Modbus异常：错误码0x{errorCode:X2}（{errorDesc}）";
                    }
                    _logger.LogError($"设备[{device.DeviceId}]解析响应失败：{errorMsg}");
                    Console.WriteLine($"设备[{device.DeviceId}]解析响应失败：{errorMsg}");
                    continue;
                }

                // 映射数据并转发
                var industrialDatas = MapToIndustrialData(device, group.Registers, rawValues);
                if (industrialDatas.Any())
                {
                    SaveAndForwardData(industrialDatas);
                }
            }
        }
        catch (OperationCanceledException)
        {
            _logger.LogError($"设备[{device.DeviceId}]连接/响应超时");
            Console.WriteLine($"设备[{device.DeviceId}]连接/响应超时");
        }
        catch (SocketException ex)
        {
            _logger.LogError(ex, $"设备[{device.DeviceId}]网络错误（IP：{device.DeviceIp}，端口：{DefaultModbusPort}）");
            Console.WriteLine($"设备[{device.DeviceId}]网络错误：{ex.Message}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"设备[{device.DeviceId}]采集异常");
            Console.WriteLine($"设备[{device.DeviceId}]采集异常：{ex.Message}");
        }
        finally
        {
            // 确保流和连接正确关闭
            if (deviceStream != null)
            {
                try
                {
                    await deviceStream.FlushAsync(stoppingToken);
                    deviceStream.Dispose();
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, $"设备[{device.DeviceId}]流释放异常");
                }
            }

            if (deviceTcpClient.Connected)
            {
                try
                {
                    deviceTcpClient.Client.Shutdown(SocketShutdown.Both);
                    await Task.Delay(100, stoppingToken); // 等待关闭确认
                }
                catch { }
                finally
                {
                    deviceTcpClient.Close();
                }
            }

            _logger.LogInformation($"设备[{device.DeviceId}]连接已关闭");
            Console.WriteLine($"设备[{device.DeviceId}]连接已关闭");
        }

        await Task.Delay(500, stoppingToken);
    }

    private List<(List<RegisterConfig> Registers, string StartAddr, string EndAddr, int Count)> GroupRegistersByContinuousAddress(List<RegisterConfig> registers)
    {
        var groups = new List<(List<RegisterConfig>, string, string, int)>();
        if (registers == null || !registers.Any()) return groups;

        // 筛选有效寄存器并排序
        var validRegisters = registers
            .Where(r => !string.IsNullOrEmpty(r.RegisterAddress) &&
                       ushort.TryParse(r.RegisterAddress, out _))
            .OrderBy(r => ushort.Parse(r.RegisterAddress))
            .ToList();

        // 记录无效寄存器
        var invalidRegisters = registers.Except(validRegisters).ToList();
        if (invalidRegisters.Any())
        {
            _logger.LogWarning($"设备寄存器无效地址：{string.Join(", ", invalidRegisters.Select(r => r.RegisterAddress))}，已过滤");
        }

        if (!validRegisters.Any()) return groups;

        // 分组连续地址的寄存器
        var currentGroup = new List<RegisterConfig> { validRegisters[0] };
        ushort currentStart = ushort.Parse(validRegisters[0].RegisterAddress);
        ushort currentEnd = currentStart;

        for (int i = 1; i < validRegisters.Count; i++)
        {
            ushort addr = ushort.Parse(validRegisters[i].RegisterAddress);
            if (addr == currentEnd + 1 && currentGroup.Count < ModbusMaxRegisterCount)
            {
                currentGroup.Add(validRegisters[i]);
                currentEnd = addr;
            }
            else
            {
                groups.Add((currentGroup, currentStart.ToString(), currentEnd.ToString(), currentGroup.Count));
                currentGroup = new List<RegisterConfig> { validRegisters[i] };
                currentStart = addr;
                currentEnd = addr;
            }
        }

        // 添加最后一组
        if (currentGroup.Count > 0)
        {
            if (currentGroup.Count > ModbusMaxRegisterCount)
            {
                // 超过最大数量时拆分
                int splitCount = (int)Math.Ceiling((double)currentGroup.Count / ModbusMaxRegisterCount);
                for (int i = 0; i < splitCount; i++)
                {
                    var splitGroup = currentGroup.Skip(i * ModbusMaxRegisterCount).Take(ModbusMaxRegisterCount).ToList();
                    if (splitGroup.Any())
                    {
                        ushort splitStart = ushort.Parse(splitGroup.First().RegisterAddress);
                        ushort splitEnd = ushort.Parse(splitGroup.Last().RegisterAddress);
                        groups.Add((splitGroup, splitStart.ToString(), splitEnd.ToString(), splitGroup.Count));
                    }
                }
            }
            else
            {
                groups.Add((currentGroup, currentStart.ToString(), currentEnd.ToString(), currentGroup.Count));
            }
        }

        return groups;
    }
    #endregion

    #region 数据映射与转发
    private List<IndustrialData> MapToIndustrialData(DeviceConfig device, List<RegisterConfig> registers, List<short> rawValues)
    {
        var datas = new List<IndustrialData>();
        if (registers == null || rawValues == null) return datas;

        for (int i = 0; i < registers.Count && i < rawValues.Count; i++)
        {
            var reg = registers[i];
            double rawValue = rawValues[i];
            double actualValue = rawValue * reg.Scale;

            datas.Add(new IndustrialData
            {
                DeviceId = device.DeviceId,
                DeviceIp = device.DeviceIp,
                RegisterAddress = reg.RegisterAddress,
                DataName = reg.DataName,
                RawValue = rawValue,
                ActualValue = actualValue,
                Unit = reg.Unit,
                Timestamp = DateTime.Now
            });
        }

        return datas;
    }

    private void SaveAndForwardData(List<IndustrialData> datas)
    {
        if (datas == null || !datas.Any()) return;

        // 保存数据到队列
        foreach (var data in datas)
        {
            _dataQueue.Enqueue(data);
            _logger.LogInformation($"采集到数据：{data.DataName}={data.ActualValue}{data.Unit}（设备IP：{data.DeviceIp}，寄存器：{data.RegisterAddress}）");
        }

        // 限制队列最大长度
        if (_dataQueue.Count > MaxDataQueueCount)
        {
            int removeCount = _dataQueue.Count - MaxDataQueueCount;
            for (int i = 0; i < removeCount; i++)
            {
                _dataQueue.TryDequeue(out _);
            }
            _logger.LogInformation($"数据队列超上限（{MaxDataQueueCount}），移除{removeCount}条旧数据");
            Console.WriteLine($"数据队列超上限（{MaxDataQueueCount}），移除{removeCount}条旧数据");
        }

        // 异步转发数据到客户端
        _ = ForwardToAllClientsAsync(datas, CancellationToken.None);
    }

    private async Task ForwardToAllClientsAsync(List<IndustrialData> datas, CancellationToken stoppingToken)
    {
        if (datas == null || !datas.Any()) return;
        if (!_clientConnections.Any())
        {
            _logger.LogInformation("无在线客户端，跳过数据转发");
            Console.WriteLine("无在线客户端，跳过数据转发");
            return;
        }

        // 序列化数据
        string jsonData;
        try
        {
            jsonData = JsonSerializer.Serialize(datas, _jsonOptions);
            _logger.LogDebug($"待转发JSON：{jsonData}"); // 调试用，生产环境可注释
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "数据JSON序列化失败，跳过转发");
            Console.WriteLine($"数据JSON序列化失败：{ex.Message}，跳过转发");
            return;
        }

        byte[] dataBytes = Encoding.UTF8.GetBytes(jsonData + "\n");
        int totalBytes = dataBytes.Length;
        _logger.LogInformation($"准备转发数据（{totalBytes}字节）给{_clientConnections.Count}个客户端");
        Console.WriteLine($"准备转发数据（{totalBytes}字节）给{_clientConnections.Count}个客户端");

        // 验证数据有效性
        if (totalBytes == 0 || totalBytes > 1024 * 10) // 限制最大10KB
        {
            _logger.LogWarning($"转发数据无效（长度：{totalBytes}字节），跳过转发");
            Console.WriteLine($"转发数据无效（长度：{totalBytes}字节），跳过转发");
            return;
        }

        // 转发给所有客户端
        foreach (var (clientId, conn) in _clientConnections.ToList())
        {
            if (stoppingToken.IsCancellationRequested) break;

            if (conn == null || !conn.Client.Connected)
            {
                CleanClientConnection(clientId, conn);
                continue;
            }

            try
            {
                // 循环发送，确保所有字节发送完毕
                int bytesSent = 0;
                ReadOnlyMemory<byte> dataMemory = new ReadOnlyMemory<byte>(dataBytes);

                while (bytesSent < totalBytes && !stoppingToken.IsCancellationRequested)
                {
                    int remainingBytes = totalBytes - bytesSent;
                    // 使用优化的WriteAsync重载
                    await conn.Stream.WriteAsync(dataMemory.Slice(bytesSent, remainingBytes), stoppingToken);
                    bytesSent += remainingBytes;
                }

                // 验证是否发送完整
                if (bytesSent != totalBytes)
                {
                    _logger.LogError($"转发客户端[{clientId}]不完整：已发{bytesSent}/{totalBytes}字节");
                    CleanClientConnection(clientId, conn);
                    continue;
                }

                conn.LastActiveTime = DateTime.Now;
                _logger.LogDebug($"数据已完整转发给客户端[{clientId}]");
                Console.WriteLine($"数据已完整转发给客户端[{clientId}]");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"转发数据给客户端[{clientId}]失败");
                Console.WriteLine($"转发数据给客户端[{clientId}]失败：{ex.Message}");
                CleanClientConnection(clientId, conn);
            }
        }
    }
    #endregion

    #region 辅助方法
    private ushort GetNextTransactionId()
    {
        int nextIntId = Interlocked.Increment(ref _transactionId);
        if (nextIntId > ushort.MaxValue)
        {
            Interlocked.Exchange(ref _transactionId, 1);
            return 1;
        }
        return (ushort)nextIntId;
    }

    private string GetModbusErrorCodeDesc(byte errorCode)
    {
        return errorCode switch
        {
            0x01 => "非法功能（设备不支持该功能码）",
            0x02 => "非法数据地址（寄存器地址不存在）",
            0x03 => "非法数据值（如寄存器数量超上限）",
            0x04 => "从站设备故障（设备内部错误）",
            0x05 => "确认（仅写操作）",
            0x06 => "从站设备忙（处理其他请求中）",
            _ => "未知错误"
        };
    }
    #endregion

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        // 停止定时器
        _pollingTimer?.Dispose();

        // 停止TCP服务器
        _tcpServer.Stop();
        _logger.LogInformation($"TCP服务器已停止监听（{_config.TcpServer.Ip}:{_config.TcpServer.Port}）");
        Console.WriteLine($"TCP服务器已停止监听（{_config.TcpServer.Ip}:{_config.TcpServer.Port}）");

        // 清理所有客户端连接
        foreach (var clientId in _clientConnections.Keys.ToList())
        {
            CleanClientConnection(clientId);
        }
        _clientConnections.Clear();
        _logger.LogInformation("所有客户端连接已清理");
        Console.WriteLine("所有客户端连接已清理");

        await base.StopAsync(cancellationToken);
        _logger.LogInformation("TcpPollingAndForwardService已完全停止");
        Console.WriteLine("TcpPollingAndForwardService已完全停止");
    }

    public List<IndustrialData> GetLatestData(int count = 10)
    {
        count = Math.Clamp(count, 1, 1000); // 限制获取数量范围
        return _dataQueue.ToList()
            .OrderByDescending(d => d.Timestamp)
            .Take(count)
            .ToList();
    }
}
